package threads.demo01;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo {

    private volatile static int amount = 0;
    private static Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < 2; i++) {
            Thread thread = new Thread(LockDemo::inc);
            thread.setName("线程" + i);
            thread.start();
        }

        TimeUnit.SECONDS.sleep(3);
        System.out.println(amount);
    }

    public static void inc() {
        // 多线程环境调试时, 鼠标右键断点,在 suspend 选项选择 Thread
        lock.lock();
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + " 获取锁成功");
        for (int i = 0; i < 100; i++) {
            amount++;
        }
        System.out.println(threadName + " 准备释放锁");
        lock.unlock();
    }

}
